<template>
  <div class="report-container">
    <el-row>
      <el-col :span="24" style="margin-bottom: 10px">
        <div>
          <el-date-picker
            v-model="reportDate"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          <el-button type="primary" style="margin-left: 10px" @click="makeReport(1)">日报表</el-button>
          <el-button type="primary" @click="makeReport(2)">月报表</el-button>
          <el-button type="primary" @click="makeReport(3)">年报表</el-button>
          <el-button type="primary" @click="getexcel()" :loading="downloadLoading">导出表格</el-button>
          <span class="load_text" v-show="loadData">数据拼命加载中,请等待...</span>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-aside width="100%" style="background-color:#ffffff">
          <el-tree
          class="tree-div"
          :data="treeData"
          show-checkbox
          element-loading-text="数据拼命加载中..."
          element-loading-spinner="el-icon-loading"
          ref="tree"
          v-loading="loadingTree"
          node-key="deviceId"
          :check-strictly="true"
          :props="defaultProps"
        />
        </el-aside>
      </el-col>
      <el-col :span="18">
        <div class="table-div">
          <fixed-thead ref="fixedtable"></fixed-thead>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import FixedThead from '@/components/FixedThead'
import { parseTime } from '@/utils'
import { findDevices, findReport } from '@/api/tdevice'
import { export_json_to_excel } from '@/vendor/Export2Excel.js'
// import { findReport } from '../../api/tenergy'
export default {
  components: { FixedThead },
  name: 'report',
  mounted () {
    this.requestDeviceList()
  },
  data () {
    return {
      loadingTree: true,
      downloadLoading: false,
      loadData: false,
      treeData: [],
      tableData: {},
      reportDate: '',
      tableDaily: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
      tableMonthly: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
      tableYearly: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
      tableResponse: [],
      excelRowList: ['Machines Name'],
      excelFieldList: ['deviceName'],
      defaultProps: {
        children: 'childList',
        label: 'deviceName'
      }
    }
  },
  methods: {
    getexcel () {
      this.downloadLoading = true
      this.excelRowList = this.excelRowList.concat(this.tableData.header)
      this.excelFieldList = this.excelFieldList.concat(this.tableData.header)
      const tHeader = this.excelRowList
      const filterVal = this.excelFieldList
      const list = this.tableData.listData
      const data = this.formatJson(filterVal, list)
      export_json_to_excel({
        header: tHeader,
        data,
        filename: this.filename,
        autoWidth: true,
        bookType: 'xlsx'
      })
      this.downloadLoading = false
      this.excelRowList.splice(1, this.excelRowList.length)
      this.excelFieldList.splice(1, this.excelFieldList.length)
    },
    /*
 */
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
          // 格式化时间戳
        } else {
          return v[j]
        }
      }))
    },
    async requestDeviceList () {
      try {
        const res = await findDevices()
        console.log(res)
        this.treeData = res.data
        this.loadingTree = false
      } catch (error) {
        console.log(error)
        this.loadingTree = false
      }
    },
    /*
    按时间和设备名称查询报表数据
    @ param type 1-day 2-month 3-year
  */
    async makeReport (type) {
      let params = {}
      // 获取选中列表所组成的数组
      let checkArray = this.$refs.tree.getCheckedKeys()
      // 设备或者时间未选择无法发送请求
      if (!this.reportDate) {
        this.showDialog('请选择您想查询的日期!')
        return
      }
      if (checkArray.length === 0) {
        this.showDialog('请选择您想查询的设备!')
      }
      // 控制报表加载提醒文字的span标签的显示
      this.loadData = true
      this.tableResponse = []
      // 准备请求报表需要的请求数据
      params.date = this.reportDate
      params.deviceIds = checkArray.toString()
      params.type = type
      try {
        const res = await findReport(params)
        console.log(res)
        this.loadData = false
        let data = res.data
        // 将接口数据转换成需要的格式
        for (let i = 0; i < data.length; i++) {
          let childObj = {}
          // 保存设备名称到对象
          childObj.deviceName = data[i].deviceName
          // 保存设备数据到对象
          let resultChild = data[i].valueList
          console.log(resultChild)
          console.log(type)
          if (type === 1) {
            console.log('进入if语句')
            for (let j = 0; j < 24; j++) {
              console.log('进入一级for循环')
              // 当为天时，遍历24次，若数据不足24次，就跳出循环
              childObj[this.tableDaily[j]] = 0
              console.log(childObj)
              for (let k = 0; k < resultChild.length; k++) {
                console.log('进入二级for循环')
                if (resultChild[k].hourValue === this.tableDaily[j]) {
                  // 如果有值
                  childObj[this.tableDaily[j]] = resultChild[k].energyValue
                }
              }
            }
          } else if (type === 2) {
            for (let j = 0; j < 31; j++) {
              childObj[this.tableMonthly[j]] = 0
              for (let k = 0; k < resultChild.length; k++) {
                if (resultChild[k].dateValue === this.tableMonthly[j]) { // 如果有值
                  childObj[this.tableMonthly[j]] = resultChild[k].energyValue
                }
              }
            }
          } else if (type === 3) {
            for (let j = 0; j < 12; j++) {
              childObj[this.tableYearly[j]] = 0
              for (let k = 0; k < resultChild.length; k++) {
                if (resultChild[k].monthValue === this.tableYearly[j]) {
                  // 如果有值
                  childObj[this.tableYearly[j]] = resultChild[k].energyValue
                }
              }
            }
          }
          this.tableResponse.push(childObj)
        }
        this.tableData.listData = this.tableResponse
        if (type === 1) {
          this.filename = '众联_日报表'
          // 日表头数据
          this.tableData.header = this.tableDaily
        } else if (type === 2) {
          this.filename = '众联_月报表'
          this.tableData.header = this.tableMonthly
        } else if (type === 3) {
          this.filename = '众联_年报表'
          this.tableData.header = this.tableYearly
        }
        console.log(this.tableData)
        this.$refs.fixedtable.changeForm(this.tableData)
        console.log(this.tableData)
        this.loadData = false
      } catch (error) {
        console.log(error)
        this.loadData = false
      }
    }
  }
}
</script>

<style lang="less">
.report-container {
    min-height: calc(100vh - 50px);
    width: 100%;
    padding: 20px;
    background-color: #EBEEF5;
  }
  .el-row{
    margin-bottom: 2px;
  }
  .tree-div {
    padding: 10px;
    height: calc(100vh - 150px);
  }
  .table-div {
    min-height: calc(100vh - 150px);
    background-color: #ffffff;
  }
</style>
